package com.atguigu.lease.common.result;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Component
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {



    private static class StringToEnumConverter<T extends Enum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnumConverter(Class<T> enumType) {
            this.enumType = enumType;
        }

        @SuppressWarnings("unchecked")
        @Override
        public T convert(String source) {
            if (source == null || source.trim().isEmpty()) {
                return null;
            }

            // 尝试按code转换
            try {
                int code = Integer.parseInt(source);
                // 检查枚举是否有fromCode方法
                try {
                    Method fromCodeMethod = enumType.getMethod("fromCode", Integer.class);
                    return (T) fromCodeMethod.invoke(null, code);
                } catch (NoSuchMethodException e) {
                    // 如果没有fromCode方法，回退到按名称转换
                    return (T) Enum.valueOf(enumType, source);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new IllegalArgumentException("调用 fromCode 失败: " + e.getMessage(), e);
                }
            } catch (NumberFormatException e) {
                // 如果不是数字，尝试按名称转换
                try {
                    return (T) Enum.valueOf(enumType, source.toUpperCase());
                } catch (IllegalArgumentException ex) {
                    // 如果按名称转换失败，尝试使用fromName方法（如果有）
                    try {
                        Method fromNameMethod = enumType.getMethod("fromName", String.class);
                        try {
                            return (T) fromNameMethod.invoke(null, source);
                        } catch (IllegalAccessException | InvocationTargetException e1) {
                            throw new IllegalArgumentException("调用 fromName 失败: " + e1.getMessage(), e1);
                        }
                    } catch (NoSuchMethodException e1) {
                        throw new IllegalArgumentException("无法将 '" + source + "' 转换为 " + enumType.getSimpleName());
                    }
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("转换失败: " + e.getMessage(), e);
            }
        }
    }
    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnumConverter(targetType);
    }
}
